<?php
class Administrator_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }
	
	/*Globals*/
	function login()
	{	
		//Check Cookie remember me
		if(@get_cookie('rememberme')):
			if($this->session->userdata('user_id') == ''):
				$dataUser = $this->db->get_where('user',array('user_id' => get_cookie('rememberme')),1)->row();
			   	// Create Session
				$this->built_session($dataUser);
				// Update Last Login
				$this->update_lastlogin();
			else:
				$this->rememberme();
			endif;		
		endif;
		
		//Check Session	Login
		if(!@$this->session->userdata('username') && $this->router->method!='login'):
			redirect(base_url().'login');
			exit;
		endif;
		
		//Check Permission
		$is_exist = $this->db->from('mainmenu as t')->join('submenu as j',"j.mainmenu_id=t.mainmenu_id AND j.sub_page='".$this->router->method."'")->where(array('t.main_page' => str_replace('administrator_','',$this->router->class)))->count_all_results();
		if(!empty($is_exist)):
			$dataResult = $this->db->select('t.mainmenu_id,j.submenu_id')->join('submenu as j',"j.mainmenu_id=t.mainmenu_id AND j.sub_page='".$this->router->method."'")->get_where('mainmenu as t',array('t.main_page' => str_replace('administrator_','',$this->router->class)),1)->row();
			$generate_menu = $this->session->userdata('generate_menu');
			if(empty($generate_menu[$dataResult->mainmenu_id]['submenu'][$dataResult->submenu_id])):
				redirect(base_url());
			endif;			
		endif;
		
		

		if(isset($_POST) && !empty($_POST) && !empty($_POST['Contruct'])):
			$username = $this->input->post('user_login');
			$password = $this->input->post('user_pass');
			$rememberme = $this->input->post('rememberme');
					
				
			$is_exist = $this->db->from('user')->where(array('username' => $username,'password' => $password))->count_all_results();
			if(!empty($is_exist)):
				$dataUser = $this->db->get_where('user',array('username' => $username,'password' => $password),1)->row();
		   		// Create Session
				$this->built_session($dataUser);
				// Update Last Login
				$this->update_lastlogin();	
		    	// Create Cookie Remember
		    	if($rememberme=='forever') $this->rememberme();			
		  		return true;
			else:
				return false;		
			endif;
		endif;
	}
	
	function logout()
	{
		//Delete Session
		$this->session->unset_userdata('user_id');
		$this->session->unset_userdata('group_id');
		$this->session->unset_userdata('username');
		$this->session->unset_userdata('generate_menu');	
		@delete_cookie('rememberme');	
	}
	
	private function rememberme()
	{
		$mycookie = array(
			'name'  => 'rememberme',
			'value' => $this->session->userdata('user_id'),
			'expire'=> '86500'
		);
		set_cookie($mycookie);		
	}
	
	private function built_session($data)
	{
		//Get Permission
		$dataPermission = $this->db->join('mainmenu as j','j.mainmenu_id=t.mainmenu_id','left')->join('submenu as k','k.submenu_id=t.submenu_id','left')->order_by('j.mainsort_id,k.subsort_id','ASC')->get_where('group_permission as t',array('t.group_id' => $data->group_id))->result();
		
		//High Algolythm
		$generate_menu = array();
		$array_id = array();	
		foreach($dataPermission as $key => $value):
			if(!in_array($value->mainmenu_id,$array_id)):
				$generate_menu[$value->mainmenu_id] = array();
				$generate_menu[$value->mainmenu_id]['main_name'] = $value->main_name;			
				$generate_menu[$value->mainmenu_id]['main_icon'] = $value->main_icon;			
				$generate_menu[$value->mainmenu_id]['main_page'] = $value->main_page;			
				$generate_menu[$value->mainmenu_id]['submenu'] = array();
				//Add Menu in array
				$array_id[] = $value->mainmenu_id;				
			endif;
			$generate_menu[$value->mainmenu_id]['submenu'][$value->submenu_id] = array(
				'sub_name' => $value->sub_name,
				'sub_page' => $value->sub_page
			);			
		endforeach;
				
     	$data_login = array(
    		'user_id' => $data->user_id,
 			'group_id' => $data->group_id,
         	'username' => $data->username,
			'generate_menu' => $generate_menu
     	);	
  		$this->session->set_userdata($data_login);
	}
	
	private function update_lastlogin()
	{
		$datetime = date('Y-m-d H:i:s');
		// Update AdminUserInfo
		$data = array(
			'last_login' => $datetime,
			'last_ip_address' => $this->input->ip_address()
		);
  		$this->db->update('user',$data,array('user_id' => $this->session->userdata('user_id')));
	}	
	
  	function box_left_menu()
	{
		return $this->load->view("templates/".$this->folder_templates."box_left_menu/templates");	
	}
	
	function imageResize($data = array())
	{
		$this->load->library('image_lib');	
		$config['image_library'] = 'gd2';
		$config['source_image'] = $data['filepath'];
		$config['new_image'] = $data['newname'];
		$config['create_thumb'] = FALSE;
		$config['maintain_ratio'] = TRUE;
		$config['width'] = $data['width'];
		$config['height'] = $data['height'];
		$this->image_lib->initialize($config);
		$this->image_lib->resize();		
		$this->image_lib->clear();
	}
	
	function deleteImage($DB,$data=array())
	{
		$image = $this->db->select('file_name')->get_where(''.$DB.'',$data,1)->row();
		@unlink($this->upload_folder.''.$DB.'/'.$image->file_name);
		@unlink($this->upload_folder.''.$DB.'/thumbs/'.$image->file_name);				
		@unlink($this->upload_folder.''.$DB.'/original/'.$image->file_name);			
		$this->db->delete(''.$DB.'',$data);		
	}		
	/*Globals*/
	
	/*User*/
	function user_profile_edit($id)
	{
		$password = $this->input->post('newpassword');
		$datetime = date('Y-m-d H:i:s');

		/*Update user*/
		$data = array(
			'update_date' => $datetime
		);
		if(!empty($password)) $data['password'] = $password;
		$this->db->update('user',$data,array('user_id' => $id));		
	}		
	/*User*/
	
	/*Search Artist*/
	function ajax_search_artist($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('artist_info')
			->like('artist_id', $txt_search)
			->or_like('artist_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('artist_id,artist_name')
			->like('artist_id', $txt_search)
			->or_like('artist_name', $txt_search)
			->get('artist_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Artist*/
	function ajax_search_song($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('song_info')
			->like('song_id', $txt_search)
			->or_like('song_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('song_id,song_name')
			->like('song_id', $txt_search)
			->or_like('song_name', $txt_search)
			->get('song_info',20,$offset)->result();
			//Get Artist Name
			foreach($dataResult as $value):
				$dataArtist = $this->db->select('j.artist_name')
				->join('artist_info as j','j.artist_id=t.artist_id','INNER')
				->get_where('song_artist as t',array('t.song_id' => $value->song_id,'t.is_default' => '1'))
				->result();
				foreach($dataArtist as $artist):
					$value->artist_name = $artist->artist_name.',';
				endforeach;
				$value->artist_name = @rtrim($value->artist_name,',');
			endforeach;
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Album*/
	function ajax_search_album($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('album_info')
			->like('album_id', $txt_search)
			->or_like('album_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('album_id,album_name')
			->like('album_id', $txt_search)
			->or_like('album_name', $txt_search)
			->get('album_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}	
	
	/*Search News*/
	function ajax_search_news($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('news_info')
			->like('news_id', $txt_search)
			->or_like('news_subject', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('news_id,news_subject')
			->like('news_id', $txt_search)
			->or_like('news_subject', $txt_search)
			->get('news_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Chords*/
	function ajax_search_chords($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('chords_info')
			->like('chords_id', $txt_search)
			->or_like('song_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('chords_id,song_name')
			->like('chords_id', $txt_search)
			->or_like('song_name', $txt_search)
			->get('chords_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}	
	
	/*Search Video*/
	function ajax_search_video($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('video_info')
			->like('video_id', $txt_search)
			->or_like('video_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('video_id,video_name')
			->like('video_id', $txt_search)
			->or_like('video_name', $txt_search)
			->get('video_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Movie*/
	function ajax_search_movie($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('movie_info')
			->like('movie_id', $txt_search)
			->or_like('movie_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('movie_id,movie_name')
			->like('movie_id', $txt_search)
			->or_like('movie_name', $txt_search)
			->get('movie_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Gallery*/
	function ajax_search_gallery($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('gallery')
			->like('gallery_id', $txt_search)
			->or_like('gallery_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('gallery_id,gallery_name')
			->like('gallery_id', $txt_search)
			->or_like('gallery_name', $txt_search)
			->get('gallery',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Fashion*/
	function ajax_search_fashion($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('fashion')
			->like('fashion_id', $txt_search)
			->or_like('fashion_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('fashion_id,fashion_name')
			->like('fashion_id', $txt_search)
			->or_like('fashion_name', $txt_search)
			->get('fashion',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Calendar*/
	function ajax_search_calendar($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('calendar_info')
			->like('calendar_id', $txt_search)
			->or_like('calendar_subject', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('calendar_id,calendar_subject')
			->like('calendar_id', $txt_search)
			->or_like('calendar_subject', $txt_search)
			->get('calendar_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}
	
	/*Search Playlist*/
	function ajax_search_playlist($offset = null)
	{
		$txt_search = $this->input->post('txt_search');
		$offset = $this->input->post('offset');
		$page = ($offset/20)+1;
		if(!empty($txt_search)):
			$totalItems = $this->db->from('playlist_info')
			->like('playlist_id', $txt_search)
			->or_like('playlist_name', $txt_search)
			->count_all_results();
			$dataResult = $this->db->select('playlist_id,playlist_name')
			->like('playlist_id', $txt_search)
			->or_like('playlist_name', $txt_search)
			->get('playlist_info',20,$offset)->result();
			//Get All Page
			$allPage = ceil($totalItems/20);
			if($page <= $allPage):
				if($page > 1):
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
					$dataResult['prevPage'] = (($page-2) * 20);
				else:
					if($page < $allPage) $dataResult['nextPage'] = ($page * 20);
				endif;
			endif;
		else:
			$dataResult = array();
		endif;
		echo json_encode($dataResult);
		exit;
	}								
}

?>